//
//  JGSearchViewController.m
//  JGMeiTuanHD
//
//  Created by JJetGu on 15/9/20.
//  Copyright (c) 2015年 Free. All rights reserved.
//

#import "JGSearchViewController.h"
#import "UIBarButtonItem+Extension.h"
#import "JGConst.h"
#import "UIView+Extension.h"
#import "MJRefresh.h"
#import "JGDPRequestTool.h"
#import "MJExtension.h"
#import "JGDeal.h"
#import "MBProgressHUD+MJ.h"

@interface JGSearchViewController () <UISearchBarDelegate>

/** 记录当前页码 */
@property (nonatomic, assign) int  currentPage;
/** 总数 */
@property (nonatomic, assign) int  totalCount;

@end

@implementation JGSearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 设置导航栏的内容
    [self setupNav];
    
    // 集成上拉加载更多
    [self setupRefresh];

}

/**
 *  集成上拉加载更多
 */
- (void)setupRefresh
{
    // 添加上拉刷新
    [self.collectionView addFooterWithTarget:self action:@selector(loadMoreDeals)];
    [self.collectionView addHeaderWithTarget:self action:@selector(loadNewDeals)];
}

/**
 *  设置导航栏的内容
 */
- (void)setupNav
{
    // 左边的返回
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithTarget:self action:@selector(back) image:@"icon_back" highImage:@"icon_back_highlighted"];
    
    //    UIView *titleView = [[UIView alloc] init];
    //    titleView.width = 300;
    //    titleView.height = 35;
    //    titleView.backgroundColor = [UIColor redColor];
    //    self.navigationItem.titleView = titleView;
    
    // 中间的搜索框
    UISearchBar *searchBar = [[UISearchBar alloc] init];
    searchBar.placeholder = @"请输入关键词";
    searchBar.delegate = self;
    self.navigationItem.titleView = searchBar;
    //    searchBar.frame = titleView.bounds;
    //    [titleView addSubview:searchBar];
}

- (void)back {
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 搜索框代理
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    // 进入下拉刷新状态, 发送请求给服务器
    [self.collectionView headerBeginRefreshing];
    
    // 退出键盘
    [searchBar resignFirstResponder];
}

#pragma mark - 跟服务器交互
- (void)loadDeals
{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    // 每页的条数
    params[@"limit"] = @30;
    // 页码
    params[@"page"] = @(self.currentPage);
    params[@"city"] = self.cityName;
    UISearchBar *bar = (UISearchBar *)self.navigationItem.titleView;
    params[@"keyword"] = bar.text;
    
    NSLog(@"%@", params);
    
    __weak typeof(self) weakSelf = self;
    [[JGDPRequestTool sharedAPITool] request:@"v1/deal/find_deals" params:params success:^(id json) {
        weakSelf.totalCount = [json[@"total_count"] intValue];
        
        // 1.取出团购的字典数组
        NSArray *newDeals = [JGDeal objectArrayWithKeyValuesArray:json[@"deals"]];
        
        if (weakSelf.currentPage == 1) { // 清除之前的旧数据
            [weakSelf.deals removeAllObjects];
        }
        
        [weakSelf.deals addObjectsFromArray:newDeals];
        
        // 2.刷新表格
        [weakSelf.collectionView reloadData];
        
        // 3.结束上拉加载
        [weakSelf.collectionView headerEndRefreshing];
        [weakSelf.collectionView footerEndRefreshing];
        
    } failure:^(NSError *error) {
        // 1.提醒失败
        [MBProgressHUD showError:@"网络繁忙,请稍后再试" toView:self.view];
        
        // 2.结束刷新
        [weakSelf.collectionView headerEndRefreshing];
        [weakSelf.collectionView footerEndRefreshing];
        
        // 3.如果是上拉加载失败了
        if (weakSelf.currentPage > 1) {
            weakSelf.currentPage--;
        }
        
    }];
}

//上啦刷新
- (void)loadMoreDeals
{
    self.currentPage ++; //改变page而已
    
    [self loadDeals];
}

//刚开始加载或者更换了条件（城市）时,后者下拉
- (void)loadNewDeals
{
    self.currentPage = 1;
    
    [self loadDeals];
}

#pragma mark - 数据源方法
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    // 尾部控件的可见性
    self.collectionView.footerHidden = (self.deals.count == self.totalCount);
    return [super collectionView:collectionView numberOfItemsInSection:section];
}

#pragma mark - 实现父类方法
- (NSString *)emptyIcon
{
    return @"icon_deals_empty";
}

@end
